<?php
/**
 * @Name: UtilString.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace HugCode\PhpUnits\Utils;

class UtilString
{

    /**
     * @Desc 产生随机字串
     * @param int $len 长度
     * @param int $type 字串类型  0字母 1数字 2大写字母 3小写字母
     * @param string $addChars 额外字符
     * @return false|string
     * @author yashuai<1762910894@qq.com>
     */
    public static function randomString(int $len = 6, int $type = -1, string $addChars = '')
    {
        switch ($type) {
            case 0:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 1:
                $chars = str_repeat('0123456789', 3);
                break;
            case 2:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
                break;
            case 3:
                $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            default:
                $chars = 'ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789' . $addChars;
                break;
        }
        if ($len > 10) { //位数过长重复字符串一定次数
            $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
        }
        $chars = str_shuffle($chars);
        return substr($chars, 0, $len);
    }

    /**
     * 比较两个字符串的相似度
     * 返回 0-100浮点数
     * @param $first
     * @param $second
     * @return float|int
     * @author yashuai<1762910894@qq.com>
     */
    public static function similarText($first, $second)
    {
        $firstLen  = strlen($first);
        $secondLen = strlen($second);

        $percent    = 0;
        $similarLen = similar_text($first, $second, $percent);

        if ($firstLen == $secondLen) {
            return $percent;
        }

        $chgLen     = max($firstLen, $secondLen) - $similarLen;
        $newPercent = (1 - $chgLen / $firstLen) * 100;

        if ($newPercent >= 100 || $newPercent <= 0) {
            return $percent;
        }
        return $newPercent;
    }


}
